/*
	MIDAS Context Based Routing
	cbr_object.cc
	Copyright (c) 2007 Radoslaw Olgierd Schoeneich
	MEAG IT PW
*/

#include <utility>
#include <typeinfo>
#include "cbr_object.h"

#ifdef CBR_DEBUG

cbr_ObjectRegistry* cbr_ObjectRegistry::inst = (cbr_ObjectRegistry*) 0;

int cbr_ObjectRegistry::getID_(cbr_Object* obj)
{
	int ID = next_ID++;
	objects.insert(std::pair<int, cbr_Object*>(ID, obj));
	return ID;
}

void cbr_ObjectRegistry::freeID_(int ID)
{
	objects.erase(ID);
}

void cbr_ObjectRegistry::printDebug_()
{
	std::map<int, cbr_Object*>::const_iterator i, j;

	// free all CBR agents, because OTcl won't do that
	std::string agentType("3CBR");
	do {
		j = objects.end();
	
		for (i = objects.begin(); i != objects.end(); i++) {
			if (agentType == typeid(*(i->second)).name()) {
				j = i;
			}
		}

		if (j != objects.end())
			delete j->second;
	} while (j != objects.end());

	if (objects.size() == 0)
		return;

	cbr_debug("---- there are some allocated 'cbr_Object's! ----\n");
	for (i = objects.begin(); i != objects.end(); i++)
		cbr_debug(" %7d %s\n", i->first, typeid(*(i->second)).name());
	cbr_debug("-------------------------------------------------\n");
}

static cbr_ObjectRegistry registryInstance;

cbr_Object::cbr_Object()
{
	this->ID = cbr_ObjectRegistry::getID(this);
}

cbr_Object::cbr_Object(cbr_Object& obj)
{
	this->ID = cbr_ObjectRegistry::getID(this);
}

cbr_Object::~cbr_Object()
{
	cbr_ObjectRegistry::freeID(this->ID);
}

#endif	// CBR_DEBUG
